import { getSiteGroup, setSiteGroup, getCurrentSite, setCurrentSite } from '@/utils/storage'
import { getSiteSelf } from '@/api/site'
import dayjs from 'dayjs'

const state = {
  currentSite: getCurrentSite(),
  siteGroup: getSiteGroup()
}

const mutations = {
  // 设置站群
  SET_SITE_GROUP: (state, sites) => {
    setSiteGroup(sites)
    state.siteGroup = sites
  },
  // 设置当前站点
  SET_CURRENT_SITE: (state, site) => {
    setCurrentSite(site)
    state.currentSite = site
  }
}

const actions = {
  updateSiteGroup({ commit }) {
    return new Promise((resolve, reject) => {
      getSiteSelf()
        .then(res => {
          if (res.code === 20000) {
            res.data.forEach(item => {
              item.createTime ? (item.createTime = dayjs(item.createTime).format('YYYY-MM-DD hh:mm:ss')) : ''
              item.updateTime ? (item.updateTime = dayjs(item.updateTime).format('YYYY-MM-DD hh:mm:ss')) : ''
            })
            commit('SET_SITE_GROUP', res.data)
            // 未设置当前站点时，默认设置第一个站点为当前站点
            if(res.data.length > 0){
              if (!state.currentSite || !state.currentSite.id) {
                commit('SET_CURRENT_SITE', res.data[0])
              } else {
                const currentSite = res.data.find(item => item.id === state.currentSite.id)
                if (currentSite){
                  commit('SET_CURRENT_SITE', currentSite)
                } else {
                  commit('SET_CURRENT_SITE', res.data[0])
                }
              }
            } else {
              commit('SET_CURRENT_SITE', {})
            }
            resolve(res.data)
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true, //命名空间
  state,
  mutations,
  actions
}
